﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZDSoft.UPMS.Service.SystemPart;
using ZDSoft.UPMS.Model.SystemPart;
using NHibernate.Criterion;
using ZDSoft.UPMS.Core;
using ZDSoft.UPMS.Web.Helper;

namespace ZDSoft.UPMS.Web.Controllers
{
    public class RoleController : Controller
    {
        //
        // GET: /Role/

        public ActionResult Index()
        {
            return View();
        }
        public IList<ICriterion> GetName(string RoleName = "")
        {
            List<ICriterion> queryConditions = new List<ICriterion>();
            if (!string.IsNullOrEmpty(RoleName))
            {
                queryConditions.Add(new LikeExpression("Name", RoleName));
            }

            return queryConditions;
        }

        public JsonResult GetPagedName(int pageIndex, int pageSize, string strSearchProperty,
      string strSearchCondition, string strSortProperty, string strSortCondition)
        {
            string roles = Request.QueryString["rolename"].ToString();
            IList<ICriterion> queryConditions = GetName(roles);
            IList<Order> orderList = new List<Order>();
            if (strSortProperty != "")
            {
                string[] sortProperties = strSortProperty.Split(',');
                string[] sortConditions = strSortCondition.Split(',');
                orderList = new List<Order>();
                for (int i = 0; i < sortProperties.Length; i++)
                {
                    if (sortConditions[i] == "asc")
                    {
                        orderList.Add(new Order(sortProperties[i], true));
                    }
                    else
                    {
                        orderList.Add(new Order(sortProperties[i], false));
                    }
                }
            }

            int count;
            int pageNum;

            IList<Role> list = new List<Role>();
            IList<Role> Roles = Core.Container.Instance.Resolve<IRoleService>().GetPaged(queryConditions, orderList, pageIndex, pageSize, out count);
            int tmpcountI = count / pageSize;
            float temCountF = float.Parse(count.ToString()) / float.Parse(pageSize.ToString());
            if (temCountF > float.Parse(tmpcountI.ToString()))
            {
                pageNum = tmpcountI + 1;
            }
            else
            {
                pageNum = tmpcountI;
            }

            foreach (Role role in Roles)
            {
                JsonHelper.ToJaonResult<Role>(role);
                list.Add(role);
            }
            list.Add(new Role() { ID = pageNum });
            JsonResult result = this.Json(list, JsonRequestBehavior.AllowGet);
            return result;
        }

        public JsonResult GetPaged(int pageIndex, int pageSize, string strSearchProperty,
           string strSearchCondition, string strSortProperty, string strSortCondition)
        {
            IList<ICriterion> queryConditions = new List<ICriterion>();
            IList<Order> orderList = new List<Order>();
            if (strSearchProperty != "")
            {
                string[] searchProperties = strSearchProperty.Split(',');
                string[] searchConditions = strSearchCondition.Split(',');
                queryConditions = new List<ICriterion>();
                for (int i = 0; i < searchProperties.Length; i++)
                {
                    queryConditions.Add(Expression.Eq(searchProperties[i], searchConditions[i]));
                }
            }
            if (strSortProperty != "")
            {
                string[] sortProperties = strSortProperty.Split(',');
                string[] sortConditions = strSortCondition.Split(',');
                orderList = new List<Order>();
                for (int i = 0; i < sortProperties.Length; i++)
                {
                    if (sortConditions[i] == "asc")
                    {
                        orderList.Add(new Order(sortProperties[i], true));
                    }
                    else
                    {
                        orderList.Add(new Order(sortProperties[i], false));
                    }
                }
            }

            int count;
            int pageNum;

            IList<Role> list = new List<Role>();
            IList<Role> Roles = ZDSoft.UPMS.Core.Container.Instance.Resolve<IRoleService>().GetPaged(queryConditions, orderList, pageIndex, pageSize, out count);

            int tmpcountI = count / pageSize;
            float temCountF = float.Parse(count.ToString()) / float.Parse(pageSize.ToString());
            if (temCountF > float.Parse(tmpcountI.ToString()))
            {
                pageNum = tmpcountI + 1;
            }
            else
            {
                pageNum = tmpcountI;
            }

            foreach (Role role in Roles)
            {
                role.Users = null;
                role.SystemFunctions = null;
                list.Add(role);
            }
            list.Add(new Role() { ID = pageNum });
            JsonResult result = this.Json(list, JsonRequestBehavior.AllowGet);
            return result;
        }

        public ActionResult Create()
        {
            //GetAllSystemFunction();
            return View();
        }

        //[HttpPost]
        public void Creates(Role roles)
        {
            ZDSoft.UPMS.Core.Container.Instance.Resolve<IRoleService>().Create(roles);
        }


        public string ztree(IList<SystemFunction> modle)
        {
            string sun = "";
            foreach (SystemFunction one in modle)
            {
                if (one.Parent == null)
                {
                    sun += "{id:" + one.ID + ",pId:" + 0 + ",name:\"" + one.Name + "\"},";
                }
                else
                {
                    sun += "{id:" + one.ID + ",pId:" + one.Parent.ID + ",name:\"" + one.Name + "\"},";
                }
            }
            return sun;

        }


        public JsonResult GetAllSysFunctions(int id, int pid, string name, int level)
        {
            int i = 1;
            IList<SystemFunction> sysFunctions = ZDSoft.UPMS.Core.Container.Instance.Resolve<ISystemFunctionService>().FindAll();
            IList<ZTreeHelper.ZTreeNode> sysTree = new List<ZTreeHelper.ZTreeNode>();
            foreach (SystemFunction sys in sysFunctions)
            {

                //int tmpID = int.Parse(id.ToString() + sys.ID.ToString());
                id++;
                int tmpID = id;
                if (sys.Parent == null)
                {
                    if (sys.Childern.Count != 0)
                    {
                        ZTreeHelper.ZTreeNode parNode = new ZTreeHelper.ZTreeNode();
                        parNode.id = tmpID;
                        parNode.pid = id;
                        parNode.tld = sys.ID.ToString();
                        parNode.name = sys.Name;
                        parNode.Checked = false;
                        parNode.icon = "../Scripts/zTree/zTreeStyle/img/diy/user.png";
                        parNode.children = new List<ZTreeHelper.ZTreeNode>();
                        foreach (SystemFunction subSys in sys.Childern)
                        {
                            i++;
                            long subTmpID = int.Parse(tmpID.ToString() + i.ToString());
                            ZTreeHelper.ZTreeNode chiNode = new ZTreeHelper.ZTreeNode();
                            chiNode.id = subTmpID;
                            chiNode.pid = tmpID;
                            chiNode.tld = subSys.ID.ToString();
                            chiNode.name = subSys.Name;
                            chiNode.Checked = false;
                            chiNode.icon = "../Scripts/zTree/zTreeStyle/img/diy/user.png";
                            chiNode.children = new List<ZTreeHelper.ZTreeNode>();
                            parNode.children.Add(chiNode);
                        }
                        sysTree.Add(parNode);
                    }
                    else
                    {
                        ZTreeHelper.ZTreeNode node = new ZTreeHelper.ZTreeNode();
                        node.id = tmpID;
                        node.pid = id;
                        node.tld = sys.ID.ToString();
                        node.name = sys.Name;
                        node.Checked = false;
                        node.icon = "../Scripts/zTree/zTreeStyle/img/diy/user.png";
                        node.children = new List<ZTreeHelper.ZTreeNode>();
                        sysTree.Add(node);
                    }
                }
            }
            JsonResult json = this.Json(sysTree, JsonRequestBehavior.AllowGet);
            return json;
        }


        public ActionResult Update(int id)
        {

            Role model = ZDSoft.UPMS.Core.Container.Instance.Resolve<IRoleService>().FindByID(id);
            IList<SystemFunction> one = new List<SystemFunction>();
            foreach (SystemFunction entity in model.SystemFunctions)
            {
                one.Add(entity);
            }
            TempData["model"] = one;
            // GetAllSystemFunction();
            return View();
        }
        //  [HttpPost]
        public void UpdateS(Role roles)
        {
            Role model = ZDSoft.UPMS.Core.Container.Instance.Resolve<IRoleService>().FindByID(roles.ID);
            ModelUtilityHelper.Transfer(roles, model);
            ZDSoft.UPMS.Core.Container.Instance.Resolve<IRoleService>().Update(model);
        }
        public JsonResult GetById(string id)
        {
            Role modl = ZDSoft.UPMS.Core.Container.Instance.Resolve<IRoleService>().FindByID(int.Parse(id));
            modl.SystemFunctions = null;
            modl.Users = null;
            JsonResult entity = this.Json(modl, JsonRequestBehavior.AllowGet);
            return entity;
        }

        [HttpPost]
        public void UpdateIsActive(string id)
        {
            Role modl = ZDSoft.UPMS.Core.Container.Instance.Resolve<IRoleService>().FindByID(int.Parse(id));
            if (modl.IsActive == true)
            {
                modl.IsActive = false;
            }
            else
            {
                modl.IsActive = true;
            }
            ZDSoft.UPMS.Core.Container.Instance.Resolve<IRoleService>().Update(modl);

        }



        public string GetAllSysFunctionsByID(int id, int pid, string name, int level, int roleID)
        {
            int i = 0;
            string result = "[";
            IList<SystemFunction> sysFunctions = ZDSoft.UPMS.Core.Container.Instance.Resolve<ISystemFunctionService>().FindAll();
            IList<SystemFunction> rolesFunctions = ZDSoft.UPMS.Core.Container.Instance.Resolve<IRoleService>().FindByID(roleID).SystemFunctions;
            foreach (SystemFunction sys in sysFunctions)
            {
                bool sysFlag = false;
                foreach (SystemFunction roleSys in rolesFunctions)
                {
                    id++;
                    if (sys.ID == roleSys.ID)
                    {
                        int tmpID = id;
                        if (sys.Parent == null)
                        {
                            if (sys.Childern.Count != 0)
                            {
                                result += "{\"id\":" + tmpID + ",\"pid\":" + id + ",\"tld\":\"sys" + sys.ID + "\",\"name\":\"" + sys.Name
                                    + "\",\"checked\":\"true\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/user.png\",\"children\":[";
                                foreach (SystemFunction nsys in sys.Childern)
                                {
                                    bool subFlag = false;
                                    foreach (SystemFunction subSys in rolesFunctions)
                                    {
                                        i++;
                                        if (nsys.ID == subSys.ID)
                                        {
                                            int subTmpID = i;
                                            result += "{\"id\":" + subTmpID + ",\"pid\":" + tmpID + ",\"tld\":\"sys" + subSys.ID + "\",\"name\":\"" + subSys.Name
                                            + "\",\"checked\":\"true\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/course.png\"},";
                                            subFlag = true;
                                        }
                                    }
                                    if (subFlag == false)
                                    {
                                        int subTmpID = i;
                                        result += "{\"id\":" + subTmpID + ",\"pid\":" + tmpID + ",\"tld\":\"sys" + nsys.ID + "\",\"name\":\"" + nsys.Name
                                            + "\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/course.png\"},";
                                    }
                                }
                                result = result.Substring(0, result.Length - 1);
                                result += "]},";
                            }
                            else
                            {
                                result += "{\"id\":" + tmpID + ",\"pid\":" + id + ",\"tld\":\"sys" + sys.ID + "\",\"name\":\"" + sys.Name
                                    + "\",\"checked\":\"true\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/user.png\"},";
                            }
                        }
                        sysFlag = true;
                    }
                }
                if (sysFlag == false)
                {
                    int tmpID = int.Parse(id.ToString() + sys.ID.ToString());
                    if (sys.Parent == null)
                    {
                        if (sys.Childern.Count != 0)
                        {
                            result += "{\"id\":" + tmpID + ",\"pid\":" + id + ",\"tld\":\"sys" + sys.ID + "\",\"name\":\"" + sys.Name
                                + "\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/user.png\",\"children\":[";
                            foreach (SystemFunction subSys in sys.Childern)
                            {
                                int subTmpID = int.Parse(tmpID.ToString() + subSys.ID.ToString());
                                result += "{\"id\":" + subTmpID + ",\"pid\":" + tmpID + ",\"tld\":\"sys" + subSys.ID + "\",\"name\":\"" + subSys.Name
                                + "\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/course.png\"},";
                            }
                            result = result.Substring(0, result.Length - 1);
                            result += "]},";
                        }
                        else
                        {
                            result += "{\"id\":" + tmpID + ",\"pid\":" + id + ",\"tld\":\"sys" + sys.ID + "\",\"name\":\"" + sys.Name
                                + "\",\"icon\":\"../../Scripts/zTree/css/zTreeStyle/img/diy/user.png\"},";
                        }
                    }
                }
            }
            result = result.Substring(0, result.Length - 1);
            result += "]";
            return result;
        }


    }
}
